<template>
  <a-card>
    <a-form-model layout="horizontal" ref="searchParams" :model="searchParams">
      <a-row type="flex" justify="start" :gutter="15">
        <a-col :md="3" :sm="24">
          <a-form-model-item>
            <a-select :options="distributors" v-model="searchParams.distributor"/>
          </a-form-model-item>
        </a-col>
        <a-col :md="4" :sm="24">
          <a-form-model-item>
            <a-range-picker :placeholder="[$t('checkin'),$t('checkout')]" :default-value="[searchParams.checkinDate,searchParams.checkoutDate]" @change="dateChange" />
          </a-form-model-item>
        </a-col>
        <a-col :md="2" :sm="24">
          <a-form-model-item>
            <a-select :options="roomCounts" v-model="searchParams.roomGuest.count"/>
          </a-form-model-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-model-item>
            <a-popover placement="bottom">
              <template slot="content">
                <p>
                  <a-input-number v-model="searchParams.roomGuest.adults" :min="1" :max="6" :precision="0" :formatter="value => `${value} 成人`" :parser="value => value.replace(' 成人', '')" />
                </p>
                <p>
                  <a-input-number v-model="searchParams.roomGuest.children" :min="0" :max="6" :precision="0" :formatter="value => `${value} 儿童`" :parser="value => value.replace(' 儿童', '')" @change="childChange" />
                </p>
                <p v-for="(item,index) in searchParams.roomGuest.childrenAges" v-bind:key="index">
                  <a-input-number :default-value="item" :min="0" :max="17" :precision="0" :formatter="value => `${value} 岁`" :parser="value => value.replace(' 岁', '')" @change="e => ageChange(e, index)" />
                </p>
              </template>
              <a-button>{{ searchParams.roomGuest.adults }} 成人, {{ searchParams.roomGuest.children }} 儿童</a-button>
            </a-popover>
          </a-form-model-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-model-item>
            <a-auto-complete :data-source="countryList" v-model="searchParams.roomGuest.nationality" :allowClear="true" :filter-option="filterOption" :placeholder="$t('nationality')"/>
          </a-form-model-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-model-item>
            <a-select :options="currencyCodes" v-model="searchParams.currencyCode">
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-model-item>
            <a-checkbox v-model="searchParams.addRoom">
              {{ $t('add') }}{{ $t('room') }}
            </a-checkbox>
          </a-form-model-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-model-item>
            <a-space>
              <a-button type="primary" icon="search" @click="fetchData" :loading="loading">{{ $t('search') }}</a-button>
            </a-space>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>

    <a-table size="middle" :columns="columns" :data-source="data" :pagination="false" :row-key="record => record.roomId + record.ratePlanId" :loading="loading">
      <template slot="supplier" slot-scope="text, record">
        {{record.supplierRate.supplier}}.{{record.supplierRate.hotelId}}
      </template>
      <template slot="room" slot-scope="text, record">
        <a-tooltip placement="right" v-if="record.roomId > 0">
          <template slot="title">
            <span>{{ $t('room') }}</span>
          </template>
          <span>[{{record.roomId}}].[{{record.roomNameEn}}]</span> <br />
        </a-tooltip>
        <a-tooltip placement="right">
          <template slot="title">
            <span>{{ $t('supplier') }}{{ $t('room') }}</span>
          </template>
          <span>[{{record.supplierRate.roomId}}].[{{record.supplierRate.roomName}}]</span>
        </a-tooltip>
      </template>
      <template slot="meal_desc" slot-scope="text, record">
        {{ record.mealTypeDesc }}<span v-if="record.mealCount > 0"> X {{ record.mealCount }}</span>
      </template>
      <template slot="price" slot-scope="text, record">
        <a-tooltip placement="top">
          <template slot="title">
            <span>{{ $t('selling_price') }}</span>
          </template>
          <span>{{ record.price.currency }} {{ record.price.amount | formatAmount('',2) }} </span>
        </a-tooltip>
        <a-tooltip placement="top">
          <template slot="title">
            <span>{{ $t('cost_price') }}</span>
          </template>
          <span>{{record.costPrice.currency}} {{record.costPrice.amount | formatAmount('',2) }}</span> <br />
        </a-tooltip>
        <a-tooltip placement="bottom" v-if="record.sellingPrice !== undefined">
          <template slot="title">
            <span>{{ $t('mandatory_price') }}</span>
          </template>
          <span>{{ record.sellingPrice.currency }} {{ record.sellingPrice.amount | formatAmount('',2) }} </span>
        </a-tooltip>
        <a-tooltip placement="bottom">
          <template slot="title">
            <span>{{ $t('supplier_price') }}</span>
          </template>
          <span>{{record.supplierRate.netPrice.currency}} {{record.supplierRate.netPrice.amount | formatAmount('',2) }}</span>
        </a-tooltip>
      </template>
      <template slot="cancel_time_limit" slot-scope="text, record">
        <a-tooltip placement="right">
          <template slot="title">
            <span>{{ $t('return')  + ' ' + $t('distributor')  + ' ' + $t('cancel_time_limit') }}</span>
          </template>
          <span>{{ getCancelDateTime(searchParams.checkinDate, record.freeCancellationTimeLimit) }}</span> <br />
        </a-tooltip>
        <a-tooltip placement="right">
          <template slot="title">
            <span>{{ $t('supplier') + ' ' + $t('cancel_time_limit') }}</span>
          </template>
          <span>{{ getCancelDateTime(searchParams.checkinDate, record.supplierRate.freeCancellationTimeLimit) }}</span>
        </a-tooltip>
      </template>
      <template #expandedRowRender="record">
        <p style="margin: 0">
          {{ record.supplierRate.remarks}}
          <br v-if="record.supplierRate.remarks !== undefined && record.supplierRate.remarks !== ''" />
          {{ record.supplierRate.extras}}
        </p>
      </template>
      <template slot="action" slot-scope="text, record">
        <a-button type="link" size="small" @click="confirmRate(record)">{{ $t("confirm") }}</a-button><br />
        <a-button type="link" size="small" @click="showBookForm(record)">{{ $t("book") }}</a-button>
      </template>
      <template v-for="(item, index) in columns" :slot="item.slotName">
        <span :key="index">{{ $t(item.slotName) }}</span>
      </template>
    </a-table>

    <a-modal v-model="bookFormVisible" :maskClosable="false" :title="$t('book')" :confirm-loading="confirmLoading" :okText="$t('submit')" @ok="createBook()">
      <a-form-model ref="bookForm" layout="vertical" :model="bookForm" autocomplete="off">
        <a-row :gutter="[16,0]" justify="center">
          <a-col :span="12">
            <a-form-model-item :label="$t('distributor')" prop="distributor" :rules="{ required: true, message: ' ', trigger: 'blur',}">
              <a-select v-model="bookForm.distributor" :options="distributors"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="$t('distributor_order_id')" prop="distributorOrderId" :rules="{ required: true, message: ' ', trigger: 'blur',}">
              <a-input v-model="bookForm.distributorOrderId" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item :label="$t('contacts') + $t('name')" prop="contactName">
              <a-input v-model="bookForm.contactName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item :label="$t('contacts') + $t('tel')" prop="contactPhone">
              <a-input v-model="bookForm.contactPhone" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item :label="$t('contacts') + ' Email'" prop="contactEmail">
              <a-input v-model="bookForm.contactEmail" />
            </a-form-model-item>
          </a-col>
          <div v-for="(arr, n) in bookForm.roomGuest.guestNames" :key="n">
            <a-col :span="12" v-for="(guestName,index) in bookForm.roomGuest.guestNames[n]" :key="index">
              <a-form-model-item :label="$t('guest_name') + '#' + (n + 1) + '-' + (index + 1)">
                <a-input-group>
                  <a-input style="width:50%" v-model="bookForm.roomGuest.guestNames[n][index].firstname" :placeholder="$t('firstname')" />
                  <a-input style="width:50%" v-model="bookForm.roomGuest.guestNames[n][index].lastname" :placeholder="$t('lastname')" />
                </a-input-group>
              </a-form-model-item>
            </a-col>
          </div>
          <a-col :span="24">
            <a-form-model-item :label="$t('guest_note')">
              <a-textarea v-model="bookForm.guestRequest" :auto-size="{ minRows: 3, maxRows: 10 }">
              </a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>

  </a-card>
</template>

<script>
import moment from 'moment';
import {formatAmount} from '@/utils/formatter'
import {getPublicData} from '@/services/public'
import {searchRate, confirmRate, reservation} from '@/services/booking'
import {mapGetters} from "vuex";
import {isEmpty} from "../../utils/util";

export default {
  name: "HotelBooking",
  i18n: require('../i18n'),
  computed: {
    ...mapGetters('account', ['user']),
  },
  data() {
    return {
      distributors: [],
      countryList: [],
      roomCounts: [
        { value: 1, label: '1 ' + this.$t('rooms') },
        { value: 2, label: '2 ' + this.$t('rooms') },
        { value: 3, label: '3 ' + this.$t('rooms') },
        { value: 4, label: '4 ' + this.$t('rooms') },
        { value: 5, label: '5 ' + this.$t('rooms') },
      ],
      currencyCodes:[
        {value:"CNY", label:"CNY 人民币"},
        {value:"USD", label:"USD 美元"},
        {value:"NZD", label:"NZD 新西兰元"},
        {value:"GBP", label:"GBP 英镑"},
        {value:"HKD", label:"HKD 港元"},
        {value:"JPY", label:"JPY 日元"},
        {value:"KRW", label:"KRW 韩元"},
        {value:"THB", label:"THB 泰国铢"},
      ],
      searchParams: {
        distributor: 'other',
        hotelId: this.$route.params.hotelId,
        checkinDate: moment().add(7, 'days'),
        checkoutDate: moment().add(8, 'days'),
        roomGuest: {
          count: 1,
          adults: 2,
          children: 0,
          childrenAges: [],
          nationality: 'CN'
        },
        currencyCode: 'CNY',
        addRoom: false,
      },
      loading: false,
      data: [],
      columns:[
        {
          dataIndex: 'supplierRate.supplier',
          align: 'center',
          slotName: "supplier",
          slots: {title: 'supplier'},
          scopedSlots: { customRender: 'supplier' },
          sorter: (a, b) => a.supplierRate.supplier.localeCompare(b.supplierRate.supplier),
        },
        {
          dataIndex: 'supplierRate.roomName',
          align: 'left',
          slotName: "room",
          slots: {title: 'room'},
          scopedSlots: { customRender: 'room' },
          sorter: (a, b) => a.supplierRate.roomName.localeCompare(b.supplierRate.roomName),
        },
        {
          dataIndex: 'supplierRate.allotment',
          align: 'center',
          slotName: "allotment",
          slots: {title: 'allotment'},
          sorter: (a, b) => a.supplierRate.allotment - b.supplierRate.allotment,
        },
        {
          dataIndex: 'supplierRate.maxOccupancy',
          align: 'center',
          slotName: "occupancy",
          slots: {title: 'occupancy'},
          sorter: (a, b) => a.mealType - b.mealType,
        },
        {
          dataIndex: 'mealTypeDesc',
          align: 'center',
          slotName: "meal_desc",
          slots: {title: 'meal_desc'},
          scopedSlots: { customRender: 'meal_desc' },
          sorter: (a, b) => a.mealType - b.mealType,
        },
        {
          dataIndex: 'price',
          align: 'left',
          slotName: "price",
          slots: {title: 'price'},
          scopedSlots: { customRender: 'price' },
          sorter: (a, b) => a.price.amount - b.price.amount,
        },
        {
          dataIndex: 'supplierRate.freeCancellationTimeLimit',
          align: 'center',
          slotName: "cancel_time_limit",
          slots: {title: 'cancel_time_limit'},
          scopedSlots: { customRender: 'cancel_time_limit' },
        },
        {
          dataIndex: 'ratePlanId',
          align: 'left',
          title: 'RatePlan',
        },
        {
          align:'center',
          slotName: "operation",
          slots: { title: 'operation' },
          scopedSlots: { customRender: 'action' },
        }
      ],
      confirmLoading: false,
      bookFormVisible: false,
      bookForm: {
        distributor: 'other',
        roomGuest: {},
      },
      bookFormRules: {
        distributor: [{required: true, trigger: 'blur',message:' '}],
        distributorOrderId: [{required: true, trigger: 'blur',message:' '}],
      }
    }
  },
  filters:{
    formatAmount: formatAmount
  },
  methods: {
    moment,
    getData() {
      getPublicData('sup_dis_coun').then(res => {
        const {distributors,countryList} = res.data
        this.distributors.push({label: 'other', value: 'other', text: 'other'})
        distributors.forEach(item => {
          this.distributors.push({label: item, value: item, text: item})
        })
        countryList.forEach(item => {
          this.countryList.push({label: item.countryNameEn, value: item.countryCode, text: item.countryNameEn})
        })
      }).catch(error => {
        console.log(error)
      })
    },
    fetchData(){
      this.loading = true
      searchRate(this.searchParams).then(res => {
        this.loading = false
        if(res.data.success && res.data.data !== null) {
          this.data = res.data.data
        } else {
          this.$message.error(res.data.message);
          this.data = []
        }
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    confirmRate(disRate){
      this.loading = true
      let params = JSON.parse(JSON.stringify(this.searchParams))
      params.ratePlanId = disRate.ratePlanId
      params.roomId = disRate.roomId
      confirmRate(params).then(res => {
        this.loading = false
        if(res.data.success && res.data.data !== null) {
          this.data = [ res.data.data ]
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    createBook(){
      this.$refs.bookForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          reservation(this.bookForm).then(res => {
            this.confirmLoading = false
            let orderId = res.data.data
            if(res.data.success) {
              this.$success({
                title: res.data.message + ' ' + orderId,
              });
            } else {
              this.$error({
                content: res.data.message + ' ' + orderId,
              });
            }
            if(!isEmpty(orderId))
              this.$openPage('/order/detail/' + orderId, "[" + orderId + "]")
          }).catch(error => {
            console.log(error)
            this.confirmLoading = false
          })
        } else {
          return false;
        }
      });
    },
    showBookForm(disRate){
      let params = JSON.parse(JSON.stringify(this.searchParams))
      params.ratePlanId = disRate.ratePlanId
      params.roomId = disRate.roomId

      this.bookForm.disRate = disRate
      this.bookForm = Object.assign(this.bookForm, params)
      this.bookForm.roomGuest.guestNames = []
      this.bookForm.price = disRate.price
      let num = 1;
      for(let j = 0;j < params.roomGuest.count;j ++) {
        this.bookForm.roomGuest.guestNames[j] = []
        for (let i = 0; i < params.roomGuest.adults; i++) {
          this.bookForm.roomGuest.guestNames[j][i] = {firstname: 'test' + num, lastname: 'test' + num}
          num++
        }
      }
      this.bookForm.contactName = this.user.userName
      this.bookForm.contactPhone = this.user.userPhone
      this.bookForm.contactEmail = this.user.userEmail
      this.bookFormVisible = true
      console.log(this.bookForm)
    },
    dateChange(date, dateArr) {
      this.searchParams.checkinDate = dateArr[0]
      this.searchParams.checkoutDate = dateArr[1]
    },
    getCancelDateTime(checkinDate, freeCancellationTimeLimit){
      if(freeCancellationTimeLimit >= 87600)
        return '-'

      let checkin = moment(checkinDate).add(1,'days').format('YYYY-MM-DD')
      return moment(checkin).add(0 - freeCancellationTimeLimit, 'hours').format('YYYY-MM-DD HH:mm')
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      );
    },
    childChange(value) {
      let ages = this.searchParams.roomGuest.childrenAges
      if(ages.length > value) {
        this.searchParams.roomGuest.childrenAges.splice(value);
      }else {
        for (let n = ages.length; n < value; n++) {
          this.searchParams.roomGuest.childrenAges.push(0)
        }
      }
    },
    ageChange(value, index) {
      this.searchParams.roomGuest.childrenAges[index] = value
    }
  },
  created() {
    this.getData()
  }
}
</script>